package com.project.demo.service.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.project.demo.constant.FindConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.*;

/**
 */
@Slf4j
public class BaseService<E>{

    @Autowired
    @PersistenceContext
    private EntityManager entityManager;

    Class<E> eClass = (Class<E>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    private final String table = humpToLine(eClass.getSimpleName());

    public Query runEntitySql(String sql){
        return entityManager.createNativeQuery(sql, eClass);
    }

    public Query runCountSql(String sql){
        return entityManager.createNativeQuery(sql);
    }

    public void insert(Map<String,Object> body){
        if (body == null || body.isEmpty()) {
            log.warn("[{}] - 插入操作：数据为空", table);
            throw new IllegalArgumentException("插入数据不能为空");
        }
        
        StringBuffer sql = new StringBuffer("INSERT INTO ");
        sql.append("`").append(table).append("`").append(" (");
        
        // 构建字段列表
        for (Map.Entry<String,Object> entry:body.entrySet()){
            String columnName = humpToLine(entry.getKey());
            sql.append("`").append(columnName).append("`").append(",");
        }
        sql.deleteCharAt(sql.length()-1);
        sql.append(") VALUES (");
        
        // 构建值列表
        for (Map.Entry<String,Object> entry:body.entrySet()){
            Object value = entry.getValue();
            
            if (value == null) {
                sql.append("NULL").append(",");
            } else if (value instanceof String){
                // 转义单引号和反斜杠，防止 SQL 注入
                String strValue = value.toString();
                // 转义单引号（MySQL需要两个单引号表示一个单引号）
                strValue = strValue.replace("\\", "\\\\").replace("'", "''");
                sql.append("'").append(strValue).append("'").append(",");
            } else if (value instanceof Number) {
                // 数字类型直接使用
                sql.append(value).append(",");
            } else if (value instanceof Boolean) {
                // 布尔类型转换为0或1
                sql.append(((Boolean)value) ? 1 : 0).append(",");
            } else {
                // 其他类型转为字符串处理
                String strValue = value.toString().replace("\\", "\\\\").replace("'", "''");
                sql.append("'").append(strValue).append("'").append(",");
            }
        }
        sql.deleteCharAt(sql.length() - 1);
        sql.append(")");
        
        String finalSql = sql.toString();
        log.info("[{}] - 插入操作，SQL：{}", table, finalSql);
        log.info("[{}] - 插入数据详情：{}", table, body);
        
        try {
            Query query = runCountSql(finalSql);
            int rowsAffected = query.executeUpdate();
            
            if (rowsAffected > 0) {
                log.info("[{}] - 插入成功，影响行数：{}", table, rowsAffected);
            } else {
                log.warn("[{}] - 插入操作执行完成，但影响行数为0", table);
                throw new RuntimeException("插入操作未影响任何行，可能插入失败");
            }
        } catch (Exception e) {
            log.error("[{}] - 插入操作失败，SQL：{}", table, finalSql, e);
            throw new RuntimeException("数据库插入失败: " + e.getMessage(), e);
        }
    }

    @Transactional
    public void update(Map<String,String> query,Map<String,String> config,Map<String,Object> body){
        if (body == null || body.isEmpty()) {
            log.warn("[{}] - 更新操作：更新数据为空", table);
            return;
        }
        
        StringBuffer sql = new StringBuffer("UPDATE ").append("`").append(table).append("`").append(" SET ");
        for (Map.Entry<String,Object> entry:body.entrySet()){
            Object value = entry.getValue();
            String columnName = humpToLine(entry.getKey());
            
            if (value == null) {
                sql.append("`").append(columnName).append("`").append("=NULL").append(",");
            } else if (value instanceof String){
                // 转义单引号和反斜杠，防止 SQL 注入
                String strValue = value.toString();
                strValue = strValue.replace("\\", "\\\\").replace("'", "''");
                sql.append("`").append(columnName).append("`").append("=").append("'").append(strValue).append("'").append(",");
            } else if (value instanceof java.sql.Timestamp || value instanceof java.util.Date) {
                // 处理Timestamp和Date类型
                java.sql.Timestamp timestamp;
                if (value instanceof java.sql.Timestamp) {
                    timestamp = (java.sql.Timestamp) value;
                } else {
                    timestamp = new java.sql.Timestamp(((java.util.Date) value).getTime());
                }
                // MySQL datetime格式：'YYYY-MM-DD HH:MM:SS'
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String timestampStr = sdf.format(timestamp);
                sql.append("`").append(columnName).append("`").append("=").append("'").append(timestampStr).append("'").append(",");
            } else if (value instanceof Number) {
                // 数字类型直接使用
                sql.append("`").append(columnName).append("`").append("=").append(value).append(",");
            } else if (value instanceof Boolean) {
                // 布尔类型转换为0或1
                sql.append("`").append(columnName).append("`").append("=").append(((Boolean)value) ? 1 : 0).append(",");
            } else {
                // 其他类型转为字符串处理
                String strValue = value.toString().replace("\\", "\\\\").replace("'", "''");
                sql.append("`").append(columnName).append("`").append("=").append("'").append(strValue).append("'").append(",");
            }
        }
        sql.deleteCharAt(sql.length()-1);
        sql.append(toWhereSql(query,"0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
        
        String finalSql = sql.toString();
        log.info("[{}] - 更新操作，SQL：{}", table, finalSql);
        log.info("[{}] - 更新数据详情：{}", table, body);
        log.info("[{}] - 查询条件：{}", table, query);
        
        try {
            Query query1 = runCountSql(finalSql);
            int rowsAffected = query1.executeUpdate();
            
            // 强制刷新EntityManager，确保更改立即生效
            try {
                entityManager.flush();
            } catch (Exception flushEx) {
                log.warn("[{}] - EntityManager flush失败（可能是正常情况）: {}", table, flushEx.getMessage());
            }
            
            if (rowsAffected > 0) {
                log.info("[{}] - 更新成功，影响行数：{}", table, rowsAffected);
            } else {
                log.warn("[{}] - 更新操作执行完成，但影响行数为0，可能没有匹配的记录或数据未变化", table);
                log.warn("[{}] - SQL：{}", table, finalSql);
                log.warn("[{}] - 查询条件：{}", table, query);
                log.warn("[{}] - 请检查：1) WHERE条件是否正确 2) 字段名是否正确 3) 值是否匹配", table);
                
                // 如果是user_participation表，输出更详细的调试信息
                if ("user_participation".equalsIgnoreCase(table)) {
                    log.error("[{}] - 更新失败详细信息：", table);
                    log.error("  - 表名：{}", table);
                    log.error("  - SQL：{}", finalSql);
                    log.error("  - 查询条件Map：{}", query);
                    log.error("  - 更新数据Map：{}", body);
                    
                    // 尝试用原始查询条件查询记录是否存在
                    try {
                        Query checkQuery = select(query, new HashMap<>());
                        long count = checkQuery.getResultList().size();
                        log.error("  - 使用相同查询条件查询到的记录数：{}", count);
                        if (count == 0) {
                            log.error("  - 警告：没有找到匹配的记录！WHERE条件可能有问题！");
                        }
                    } catch (Exception checkEx) {
                        log.error("  - 验证查询失败：{}", checkEx.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.error("[{}] - 更新操作失败，SQL：{}", table, finalSql, e);
            log.error("[{}] - 查询条件：{}", table, query);
            log.error("[{}] - 更新数据：{}", table, body);
            throw new RuntimeException("数据库更新失败: " + e.getMessage(), e);
        }
    }

    public Map<String,Object> selectToPage(Map<String,String> query,Map<String,String> config){
        Query select = select(query, config);
        Map<String,Object> map = new HashMap<>();
        map.put("list",select.getResultList());
        config.remove(FindConfig.GROUP_BY);
        map.put("count",count(query,config).getSingleResult());
        return map;
    }

    public List<Map<String,Object>> selectToList(Map<String,String> query,Map<String,String> config){
        Query select = selectGroupCount(query, config);
        List<Map<String,Object>> list = new ArrayList<>();
        List<Object[]> resultList = select.getResultList();
        for (Object[] object: resultList) {
            Map<String,Object> mapSub = new HashMap<>();
            mapSub.put(config.get(FindConfig.GROUP_BY),object[1]);
            mapSub.put("count",object[0]);
            mapSub.put("0",object[0]);
            mapSub.put("1",object[1]);
            list.add(mapSub);
        }
        return list;
    }

    public Map<String,Object> selectBarGroup(Map<String,String> query,Map<String,String> config){
        Query select = barGroup(query, config);
        Map<String,Object> map = new HashMap<>();
        map.put("list",select.getResultList());
        return map;
    }

    public Query barGroup(Map<String,String> query,Map<String,String> config){
        StringBuffer sql = new StringBuffer(" SELECT ");
        if (config.get(FindConfig.GROUP_BY) != null && !"".equals(config.get(FindConfig.GROUP_BY))){
            sql.append(config.get(FindConfig.GROUP_BY));
            if (config.get(FindConfig.FIELD) != null && !"".equals(config.get(FindConfig.FIELD))){
                String[] fieldList = config.get(FindConfig.FIELD).split(",");
                for (int i=0;i<fieldList.length;i++)
                    sql.append(" ,SUM(").append(fieldList[i]).append(")");
            }
            sql.append(" FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
            sql.append(" ").append("GROUP BY ").append(config.get(FindConfig.GROUP_BY));
        }else {
            sql.append(" SUM(").append(config.get(FindConfig.GROUP_BY)).append(") FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
        }
        log.info("[{}] - 查询操作，sql: {}",table,sql);
        return runCountSql(sql.toString());
    }

    public Query selectGroupCount(Map<String,String> query,Map<String,String> config){
        StringBuffer sql = new StringBuffer("select COUNT(*) AS count_value, ");
        sql.append(config.get(FindConfig.GROUP_BY)).append(" ");
        sql.append("from ").append("`").append(table).append("` ");
        sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
        if (config.get(FindConfig.GROUP_BY) != null && !"".equals(config.get(FindConfig.GROUP_BY))){
            sql.append("group by ").append(config.get(FindConfig.GROUP_BY)).append(" ");
        }
        log.info("[{}] - 查询操作，sql: {}",table,sql);
        return runCountSql(sql.toString());
    }

    public Query select(Map<String,String> query,Map<String,String> config){
        // 如果 config 为 null，创建一个空的 HashMap 避免空指针异常
        if (config == null) {
            config = new HashMap<>();
        }
        StringBuffer sql = new StringBuffer("select ");
        sql.append(config.get(FindConfig.FIELD) == null || "".equals(config.get(FindConfig.FIELD)) ? "*" : config.get(FindConfig.FIELD)).append(" ");
        sql.append("from ").append("`").append(table).append("`").append(toWhereSql(query, config != null && "0".equals(config.get(FindConfig.LIKE)), config != null ? config.get(FindConfig.SQLHWERE) : null));
        if (config.get(FindConfig.GROUP_BY) != null && !"".equals(config.get(FindConfig.GROUP_BY))){
            sql.append("group by ").append(config.get(FindConfig.GROUP_BY)).append(" ");
        }
        if (config.get(FindConfig.ORDER_BY) != null && !"".equals(config.get(FindConfig.ORDER_BY))){
            sql.append("order by ").append(config.get(FindConfig.ORDER_BY)).append(" ");
        }
        if (config.get(FindConfig.PAGE) != null && !"".equals(config.get(FindConfig.PAGE))){
            int page = config.get(FindConfig.PAGE) != null && !"".equals(config.get(FindConfig.PAGE)) ? Integer.parseInt(config.get(FindConfig.PAGE)) : 1;
            int limit = config.get(FindConfig.SIZE) != null && !"".equals(config.get(FindConfig.SIZE)) ? Integer.parseInt(config.get(FindConfig.SIZE)) : 10;
            sql.append(" limit ").append( (page-1)*limit ).append(" , ").append(limit);
        }
        log.info("[{}] - 查询操作，sql: {}",table,sql);
        return runEntitySql(sql.toString());
    }

    @Transactional
    public void delete(Map<String,String> query,Map<String,String> config){
        StringBuffer sql = new StringBuffer("DELETE FROM ").append("`").append(table).append("`").append(" ");
        sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.GROUP_BY)),config.get(FindConfig.SQLHWERE)));
        log.info("[{}] - 删除操作：{}",table,sql);
        Query query1 = runCountSql(sql.toString());
        query1.executeUpdate();
    }

    public Query count(Map<String,String> query,Map<String,String> config){
        // 如果 config 为 null，创建一个空的 HashMap 避免空指针异常
        if (config == null) {
            config = new HashMap<>();
        }
        StringBuffer sql = new StringBuffer("SELECT ");
        log.info("拼接统计函数前");
        if (config.get(FindConfig.GROUP_BY) != null && !"".equals(config.get(FindConfig.GROUP_BY))){
            sql.append(config.get(FindConfig.GROUP_BY)).append(" ,COUNT(").append(config.get(FindConfig.GROUP_BY)).append(") FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
            sql.append(" ").append("GROUP BY ").append(config.get(FindConfig.GROUP_BY));
        }else {
            sql.append("COUNT(*) FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
        }
        log.info("[{}] - 统计操作，sql: {}",table,sql);
        return runCountSql(sql.toString());
    }

    public Query sum(Map<String,String> query,Map<String,String> config){
        // 如果 config 为 null，创建一个空的 HashMap 避免空指针异常
        if (config == null) {
            config = new HashMap<>();
        }
        StringBuffer sql = new StringBuffer(" SELECT ");
        if (config.get(FindConfig.GROUP_BY) != null && !"".equals(config.get(FindConfig.GROUP_BY))){
            sql.append(config.get(FindConfig.GROUP_BY)).append(" ,SUM(").append(config.get(FindConfig.FIELD)).append(") FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
            sql.append(" ").append("GROUP BY ").append(config.get(FindConfig.GROUP_BY));
        }else {
            sql.append(" SUM(").append(config.get(FindConfig.FIELD)).append(") FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
        }
        log.info("[{}] - 查询操作，sql: {}",table,sql);
        return runCountSql(sql.toString());
    }

    public Query avg(Map<String,String> query,Map<String,String> config){
        StringBuffer sql = new StringBuffer(" SELECT ");
        if (config.get(FindConfig.GROUP_BY) != null && !"".equals(config.get(FindConfig.GROUP_BY))){
            sql.append(config.get(FindConfig.GROUP_BY)).append(" ,AVG(").append(config.get(FindConfig.FIELD)).append(") FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
            sql.append(" ").append("GROUP BY ").append(config.get(FindConfig.GROUP_BY));
        }else {
            sql.append(" AVG(").append(config.get(FindConfig.FIELD)).append(") FROM ").append("`").append(table).append("`");
            sql.append(toWhereSql(query, "0".equals(config.get(FindConfig.LIKE)),config.get(FindConfig.SQLHWERE)));
        }
        log.info("[{}] - 查询操作，sql: {}",table,sql);
        return runCountSql(sql.toString());
    }

    public String toWhereSql(Map<String,String> query, Boolean like,String sqlwhere) {
        if (query != null && query.size() > 0) {
            try {
                StringBuilder sql = new StringBuilder(" WHERE ");
                // 定义需要过滤的特殊参数（这些不应该作为数据库列）
                Set<String> excludedKeys = new HashSet<>(Arrays.asList(
                    "date_range", "time_dimension", "dateRange", "timeDimension"
                ));
                
                for (Map.Entry<String, String> entry : query.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    
                    if (key == null || value == null) {
                        log.warn("查询条件中的key或value为null，跳过：key={}, value={}", key, value);
                        continue;
                    }
                    
                    // 过滤掉特殊参数，这些不应该作为数据库列
                    if (excludedKeys.contains(key)) {
                        log.debug("跳过特殊参数：{}", key);
                        continue;
                    }
                    
                    if (key.contains(FindConfig.MIN_)) {
                        String min = humpToLine(key).replace("_min", "");
                        String decodedValue = URLDecoder.decode(value, "UTF-8");
                        sql.append("`").append(min).append("`").append(" >= '").append(decodedValue).append("' and ");
                        log.debug("WHERE条件 - {} >= {}", min, decodedValue);
                        continue;
                    }
                    if (key.contains(FindConfig.MAX_)) {
                        String max = humpToLine(key).replace("_max", "");
                        String decodedValue = URLDecoder.decode(value, "UTF-8");
                        sql.append("`").append(max).append("`").append(" <= '").append(decodedValue).append("' and ");
                        log.debug("WHERE条件 - {} <= {}", max, decodedValue);
                        continue;
                    }
                    
                    String columnName = humpToLine(key);
                    String decodedValue = URLDecoder.decode(value, "UTF-8");
                    
                    // 双语字段列表（存储为JSON格式的字段）
                    Set<String> bilingualFields = new HashSet<>(Arrays.asList(
                        "type", "conference_name", "meeting_venue", "meeting_type",
                        "conference_introduction", "site_equipment", "member_name",
                        "member_title", "member_affiliation", "speaker_name",
                        "speaker_position", "speaker_bio", "track_name", "topics"
                    ));
                    
                    // 如果是双语字段，使用JSON查询
                    if (bilingualFields.contains(columnName)) {
                        // 使用JSON_EXTRACT或JSON_CONTAINS来查询JSON字段
                        // 匹配中文或英文值
                        String escapedValue = decodedValue.replace("'", "''"); // 转义单引号
                        sql.append("(")
                           .append("JSON_EXTRACT(`").append(columnName).append("`, '$.zh') = '").append(escapedValue).append("'")
                           .append(" OR ")
                           .append("JSON_EXTRACT(`").append(columnName).append("`, '$.en') = '").append(escapedValue).append("'")
                           .append(" OR ")
                           .append("`").append(columnName).append("` LIKE '%\"").append(escapedValue).append("\"%'")
                           .append(")").append(" and ");
                        log.debug("WHERE条件 - {} (双语字段) JSON查询: {}", columnName, decodedValue);
                    } else if (like == true || like != null && like) {
                        sql.append("`").append(columnName).append("`").append(" LIKE '%").append(decodedValue).append("%'").append(" and ");
                        log.debug("WHERE条件 - {} LIKE '%{}%'", columnName, decodedValue);
                    } else {
                        sql.append("`").append(columnName).append("`").append(" = '").append(decodedValue).append("'").append(" and ");
                        log.debug("WHERE条件 - {} = '{}'", columnName, decodedValue);
                    }
                }
                if (sqlwhere!=null && !sqlwhere.trim().equals("")) {
                    sql.append(sqlwhere).append(" and ");
                }
                if (sql.length() > 7) { // " WHERE "的长度
                    sql.delete(sql.length() - 4, sql.length()); // 删除最后的 " and "
                    sql.append(" ");
                }
                String finalSql = sql.toString();
                log.debug("生成的WHERE SQL: {}", finalSql);
                return finalSql;
            } catch (UnsupportedEncodingException e) {
                log.error("拼接SQL失败：{}", e.getMessage(), e);
            } catch (Exception e) {
                log.error("构建WHERE SQL时发生异常：{}", e.getMessage(), e);
            }
        } else {
            if (sqlwhere!=null && !sqlwhere.trim().equals("")) {
                StringBuilder sql = new StringBuilder(" WHERE ");
                sql.append(sqlwhere);
                return sql.toString();
            }
        }
        return "";
    }

    public Map<String,Object> readBody(BufferedReader reader){
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try{
            br = reader;
            String str;
            while ((str = br.readLine()) != null){
                sb.append(str);
            }
            br.close();
            String json = sb.toString();
            return JSONObject.parseObject(json, Map.class);
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if (null != br){
                try{
                    br.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public Map<String,String> readQuery(HttpServletRequest request){
        Map<String, String> map = new HashMap<>();
        try {
            // 优先使用request.getParameterMap()，它自动处理URL编码和参数解析
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] values = entry.getValue();
                if (values != null && values.length > 0) {
                    // getParameterMap()返回的值可能已经解码，不需要再次解码
                    // 但为了安全，如果包含%字符则尝试解码
                    String value = values[0];
                    if (value != null && value.contains("%")) {
                        try {
                            value = URLDecoder.decode(value, "UTF-8");
                        } catch (Exception e) {
                            // 解码失败，使用原值
                        }
                    }
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            log.warn("使用request.getParameterMap()解析参数失败，使用备用方案", e);
            // 备用方案：手动解析QueryString
            String queryString = request.getQueryString();
            if (queryString != null && !"".equals(queryString)) {
                try {
                    String[] querys = queryString.split("&");
                    for (String query : querys) {
                        int eqIndex = query.indexOf("=");
                        if (eqIndex > 0) {
                            String key = query.substring(0, eqIndex);
                            String value = query.substring(eqIndex + 1);
                            // URL解码
                            try {
                                value = URLDecoder.decode(value, "UTF-8");
                            } catch (UnsupportedEncodingException e2) {
                                // 解码失败，使用原值
                            }
                            map.put(key, value);
                        }
                    }
                } catch (Exception e2) {
                    log.error("解析QueryString失败", e2);
                }
            }
        }
        
        // 移除配置相关的特殊参数
        map.remove(FindConfig.PAGE);
        map.remove(FindConfig.SIZE);
        map.remove(FindConfig.LIKE);
        map.remove(FindConfig.ORDER_BY);
        map.remove(FindConfig.FIELD);
        map.remove(FindConfig.GROUP_BY);
        map.remove(FindConfig.MAX_);
        map.remove(FindConfig.MIN_);
        map.remove(FindConfig.SQLHWERE);
        
        // 移除前端特殊参数，这些不应该作为数据库列
        map.remove("date_range");
        map.remove("time_dimension");
        map.remove("dateRange");
        map.remove("timeDimension");
        
        return map;
    }

    public Map<String,String> readConfig(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        map.put(FindConfig.PAGE,request.getParameter(FindConfig.PAGE));
        map.put(FindConfig.SIZE,request.getParameter(FindConfig.SIZE));
        map.put(FindConfig.LIKE,request.getParameter(FindConfig.LIKE));
        map.put(FindConfig.ORDER_BY,request.getParameter(FindConfig.ORDER_BY));
        map.put(FindConfig.FIELD,request.getParameter(FindConfig.FIELD));
        map.put(FindConfig.GROUP_BY,request.getParameter(FindConfig.GROUP_BY));
        map.put(FindConfig.MAX_,request.getParameter(FindConfig.MAX_));
        map.put(FindConfig.MIN_,request.getParameter(FindConfig.MIN_));
        map.put(FindConfig.SQLHWERE,request.getParameter(FindConfig.SQLHWERE));
        return map;
    }

    public void importDb(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return;
        }
        List<Map<String,String>> body = new ArrayList<>();
        String fileName = file.getOriginalFilename();
        if (fileName == null){
            return;
        }
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        InputStream ins = file.getInputStream();
        Workbook wb = null;
        if(suffix.equals("xlsx")){
            wb = new XSSFWorkbook(ins);
        }else{
            wb = new HSSFWorkbook(ins);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(null != sheet){
            for(int line = 0; line <= sheet.getLastRowNum();line++){
                Row row = sheet.getRow(line);
                if(null == row){
                    continue;
                }
                Iterator<Cell> cellIterator = row.cellIterator();
                StringBuffer sql = new StringBuffer("INSERT INTO ").append(table).append(" VALUES (null,");
                while (cellIterator.hasNext()){
                    sql.append(cellIterator.next().getStringCellValue()).append(",");
                }
                sql.deleteCharAt(sql.length());
                sql.append(")");
                runCountSql(sql.toString());
            }
        }
    }

    public HSSFWorkbook exportDb(Map<String,String> query,Map<String,String> config){
        Query select = select(query, config);
        List<Map<String,String>> resultList = select.getResultList();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(table);
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        for (int i = 0; i < resultList.size(); i++) {
            HSSFRow row = sheet.createRow(i);
            Map<String,String> map = resultList.get(i);
            int j = 0;
            for (Map.Entry<String,String> entry:map.entrySet()){
                row.createCell(j).setCellValue(new HSSFRichTextString(entry.getValue()));
            }
        }
        return workbook;
    }

    @Transactional
    public void save(E e){
        String s = JSONObject.toJSONString(e);
        Map map = JSONObject.parseObject(s, Map.class);
        insert(map);
    }

    public E findOne(Map<String, String> map){
        try {
            Query select = select(map, new HashMap<>());
            return (E) select.getSingleResult();
        }catch (Exception e){
            return null;
        }
    }


    public String encryption(String plainText) {
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            re_md5 = buf.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return re_md5;
    }


    public static String humpToLine(String str) {
        if (str == null) {
            return null;
        }
        // 如果已经是下划线格式（包含下划线且没有大写字母），直接返回
        // 这样可以避免对已经正确的字段名（如user_participation_id）进行不必要的转换
        if (str.contains("_") && str.equals(str.toLowerCase())) {
            return str;
        }
        // 将驼峰字符串转换成下划线格式
        char[] charArray = str.toCharArray();
        StringBuilder buffer = new StringBuilder();
        //处理字符串
        for (int i = 0, l = charArray.length; i < l; i++) {
            if (charArray[i] >= 65 && charArray[i] <= 90) {
                // 修复：避免修改原数组，直接使用转换后的字符
                buffer.append("_").append((char)(charArray[i] + 32));
            } else {
                buffer.append(charArray[i]);
            }
        }
        String s = buffer.toString();
        if (s.startsWith("_")){
            return s.substring(1);
        }else {
            return s;
        }
    }


    public JSONObject covertObject(JSONObject object) {
        if (object == null) {
            return null;
        }
        JSONObject newObject = new JSONObject();
        Set<String> set = object.keySet();
        for (String key : set) {
            Object value = object.get(key);
            if (value instanceof JSONArray) {
                //数组
                value = covertArray(object.getJSONArray(key));
            } else if (value instanceof JSONObject) {
                //对象
                value = covertObject(object.getJSONObject(key));
            }
            //这个方法自己写的改成下划线
            key = humpToLine(key);
            newObject.put(key, value);
        }
        return newObject;
    }

    public JSONArray covertArray(JSONArray array) {
        if (array == null) {
            return null;
        }
        JSONArray newArray = new JSONArray();
        for (int i = 0; i < array.size(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                //数组
                value = covertArray(array.getJSONArray(i));
            } else if (value instanceof JSONObject) {
                //对象
                value = covertObject(array.getJSONObject(i));
            }
            newArray.add(value);
        }
        return newArray;
    }


}
